import React from 'react'
import { DatePicker as FormilyDatePicker } from '@formily/antd'
import moment from 'moment'

const handleChange = (
  dates: any,
  dateStrings: any,
  format: any,
  onChange: any
) => {
  if (dates && Array.isArray(dates) && dates.length === 2) {
    // 检查格式是否为YYYY-MM-DD
    format = format || 'YYYY-MM-DD'
    if (format === 'YYYY-MM-DD' || format === 'YYYY/MM/DD') {
      const [startDate, endDate] = dates

      // 开始时间设置为00:00:00
      const startTime = startDate ? moment(startDate).format(format) : null
      const startTimeString = startTime ? `${startTime} 00:00:00` : null

      // 结束时间设置为23:59:59
      const endTime = endDate ? moment(endDate).format(format) : null
      const endTimeString = endTime ? `${endTime} 23:59:59` : null

      // 调用原始的onChange，传入处理后的时间和字符串
      ;(onChange as any)?.(
        [startTimeString, endTimeString],
        [startTimeString, endTimeString]
      )
    } else {
      // 其他格式直接传递原始值
      ;(onChange as any)?.(dates, dateStrings)
    }
  } else {
    // 非RangePicker或空值直接传递
    ;(onChange as any)?.(dates, dateStrings)
  }
}

const DatePickerBase: React.FC<
  React.ComponentProps<typeof FormilyDatePicker>
> = (props) => {
  const { onChange, format, ...restProps } = props

  return (
    <FormilyDatePicker
      {...restProps}
      onChange={(dates, dateStrings) =>
        handleChange(dates, dateStrings, format, onChange)
      }
    />
  )
}
const RangePicker: React.FC<
  React.ComponentProps<typeof FormilyDatePicker.RangePicker>
> = (props) => {
  const { onChange, format, ...restProps } = props
  return (
    <FormilyDatePicker.RangePicker
      {...restProps}
      onChange={(dates, dateStrings) =>
        handleChange(dates, dateStrings, format, onChange)
      }
    />
  )
}

export const DatePicker: any = Object.assign(DatePickerBase, { RangePicker })
